{% extends "auth/base.html" %}

{% block title %}用户管理 - FlaskWeb{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>
        <i class="fas fa-users me-2"></i>用户管理
    </h2>
    <div>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="fas fa-plus me-1"></i>添加用户
        </button>
    </div>
</div>

<div class="card shadow">
    <div class="card-header">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h5 class="mb-0">用户列表</h5>
            </div>
            <div class="col-md-6">
                <div class="input-group">
                    <input type="text" class="form-control" placeholder="搜索用户..." id="searchInput">
                    <button class="btn btn-outline-secondary" type="button" id="searchBtn">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>昵称</th>
                        <th>角色</th>
                        <th>状态</th>
                        <th>注册时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for user in users %}
                    <tr>
                        <td>{{ user.id }}</td>
                        <td>
                            <div class="d-flex align-items-center">
                                {% if user.avatar %}
                                <img src="{{ user.avatar }}" alt="Avatar" class="rounded-circle me-2" width="30" height="30">
                                {% else %}
                                <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center me-2" style="width: 30px; height: 30px;">
                                    {{ user.username[0].upper() }}
                                </div>
                                {% endif %}
                                {{ user.username }}
                            </div>
                        </td>
                        <td>{{ user.email }}</td>
                        <td>{{ user.nickname or '-' }}</td>
                        <td>
                            {% for role in user.roles %}
                            <span class="badge bg-secondary me-1">{{ role.name }}</span>
                            {% endfor %}
                        </td>
                        <td>
                            {% if user.is_active %}
                            <span class="badge bg-success">活跃</span>
                            {% else %}
                            <span class="badge bg-danger">禁用</span>
                            {% endif %}
                            {% if user.is_admin %}
                            <span class="badge bg-warning">管理员</span>
                            {% endif %}
                        </td>
                        <td>{{ user.created_at.strftime('%Y-%m-%d') if user.created_at else '-' }}</td>
                        <td>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-sm btn-outline-primary edit-user" data-user-id="{{ user.id }}">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-info manage-roles" data-user-id="{{ user.id }}">
                                    <i class="fas fa-user-tag"></i>
                                </button>
                                {% if user.id != current_user.id %}
                                <button type="button" class="btn btn-sm btn-outline-danger delete-user" data-user-id="{{ user.id }}">
                                    <i class="fas fa-trash"></i>
                                </button>
                                {% endif %}
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        {% if pagination %}
        <nav aria-label="用户列表分页">
            <ul class="pagination justify-content-center">
                {% if pagination.has_prev %}
                <li class="page-item">
                    <a class="page-link" href="{{ url_for('admin.users', page=pagination.prev_num) }}">上一页</a>
                </li>
                {% endif %}
                
                {% for page_num in pagination.iter_pages() %}
                {% if page_num %}
                {% if page_num != pagination.page %}
                <li class="page-item">
                    <a class="page-link" href="{{ url_for('admin.users', page=page_num) }}">{{ page_num }}</a>
                </li>
                {% else %}
                <li class="page-item active">
                    <span class="page-link">{{ page_num }}</span>
                </li>
                {% endif %}
                {% else %}
                <li class="page-item disabled">
                    <span class="page-link">...</span>
                </li>
                {% endif %}
                {% endfor %}
                
                {% if pagination.has_next %}
                <li class="page-item">
                    <a class="page-link" href="{{ url_for('admin.users', page=pagination.next_num) }}">下一页</a>
                </li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
    </div>
</div>

<!-- 添加用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="email" required>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码</label>
                        <input type="password" class="form-control" id="password" required>
                    </div>
                    <div class="mb-3">
                        <label for="roles" class="form-label">角色</label>
                        <select class="form-select" id="roles" multiple>
                            {% for role in all_roles %}
                            <option value="{{ role.id }}">{{ role.name }} - {{ role.description }}</option>
                            {% endfor %}
                        </select>
                        <div class="form-text">按住Ctrl键可选择多个角色</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveUserBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 管理角色模态框 -->
<div class="modal fade" id="manageRolesModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">管理用户角色</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="manageRolesForm">
                    <div class="mb-3">
                        <label for="userRoles" class="form-label">角色</label>
                        <select class="form-select" id="userRoles" multiple>
                            {% for role in all_roles %}
                            <option value="{{ role.id }}">{{ role.name }} - {{ role.description }}</option>
                            {% endfor %}
                        </select>
                        <div class="form-text">按住Ctrl键可选择多个角色</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveRolesBtn">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 搜索功能
    document.getElementById('searchBtn').addEventListener('click', function() {
        const searchTerm = document.getElementById('searchInput').value.trim();
        if (searchTerm) {
            window.location.href = `{{ url_for('admin.users') }}?search=${encodeURIComponent(searchTerm)}`;
        } else {
            window.location.href = `{{ url_for('admin.users') }}`;
        }
    });
    
    // 回车搜索
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            document.getElementById('searchBtn').click();
        }
    });
    
    // 添加用户
    document.getElementById('saveUserBtn').addEventListener('click', function() {
        const form = document.getElementById('addUserForm');
        const formData = new FormData(form);
        
        // 获取选中的角色
        const rolesSelect = document.getElementById('roles');
        const selectedRoles = Array.from(rolesSelect.selectedOptions).map(option => option.value);
        
        // 构建数据对象
        const userData = {
            username: document.getElementById('username').value,
            email: document.getElementById('email').value,
            password: document.getElementById('password').value,
            roles: selectedRoles
        };
        
        // 发送AJAX请求
        fetch('{{ url_for("api.create_user") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(userData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('addUserModal'));
                modal.hide();
                
                // 显示成功消息
                alert('用户添加成功');
                
                // 刷新页面
                window.location.reload();
            } else {
                alert('添加用户失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('添加用户失败');
        });
    });
    
    // 管理角色
    let currentUserId = null;
    
    document.querySelectorAll('.manage-roles').forEach(button => {
        button.addEventListener('click', function() {
            currentUserId = this.getAttribute('data-user-id');
            
            // 获取用户当前角色
            fetch(`{{ url_for("api.get_user_roles") }}?user_id=${currentUserId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 设置选中的角色
                    const rolesSelect = document.getElementById('userRoles');
                    Array.from(rolesSelect.options).forEach(option => {
                        option.selected = data.roles.includes(parseInt(option.value));
                    });
                    
                    // 显示模态框
                    const modal = new bootstrap.Modal(document.getElementById('manageRolesModal'));
                    modal.show();
                } else {
                    alert('获取用户角色失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取用户角色失败');
            });
        });
    });
    
    // 保存角色
    document.getElementById('saveRolesBtn').addEventListener('click', function() {
        // 获取选中的角色
        const rolesSelect = document.getElementById('userRoles');
        const selectedRoles = Array.from(rolesSelect.selectedOptions).map(option => option.value);
        
        // 发送AJAX请求
        fetch('{{ url_for("api.update_user_roles") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                user_id: currentUserId,
                roles: selectedRoles
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('manageRolesModal'));
                modal.hide();
                
                // 显示成功消息
                alert('角色更新成功');
                
                // 刷新页面
                window.location.reload();
            } else {
                alert('更新角色失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('更新角色失败');
        });
    });
    
    // 删除用户
    document.querySelectorAll('.delete-user').forEach(button => {
        button.addEventListener('click', function() {
            const userId = this.getAttribute('data-user-id');
            
            if (confirm('确定要删除此用户吗？此操作不可恢复。')) {
                fetch(`{{ url_for("api.delete_user") }}?user_id=${userId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('用户删除成功');
                        window.location.reload();
                    } else {
                        alert('删除用户失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除用户失败');
                });
            }
        });
    });
</script>
{% endblock %}